import { Button, Card, List, Modal, Popover, Space, message } from "antd"
import { useEffect, useState } from "react";
import { getSftpApi, getToken } from "./utils/client";
import type { FileInfo } from "@linksaas-minapp/ssh-proxy-api";
import { DownloadOutlined, FileOutlined, FolderAddOutlined, FolderOutlined, MoreOutlined, UploadOutlined } from "@ant-design/icons";
import MkdirModal from "./components/MkdirModal";
import UploadModal from "./components/UploadModal";
import { min_app_fs } from "@linksaas-minapp/api";
import RenameModal from "./components/RenameModal";

export interface SftpPanelProps {
    curClientId: string
}

function SftpPanel(props: SftpPanelProps) {
    const [curPath, setCurPath] = useState("");
    const [fileList, setFileList] = useState<FileInfo[]>([]);
    const [showMkdirModal, setShowMkdirModal] = useState(false);
    const [showUploadModal, setShowUploadModal] = useState(false);
    const [renamePath, setRenamePath] = useState("");
    const [removePath, setRemovePath] = useState("");

    const loadCurPath = async () => {
        const api = getSftpApi();
        const path = await api.sftpWorkDirPost({
            portforwardListPostRequest: {
                id: props.curClientId,
                token: getToken(),
            },
        });
        setCurPath(path);
        console.log(path);
    };

    const loadFileList = async () => {
        if (curPath == "") {
            setFileList([]);
            return;
        }
        const api = getSftpApi();
        const res = await api.sftpListDirPost({
            sftpListDirPostRequest: {
                id: props.curClientId,
                token: getToken(),
                path: curPath,
            },
        });
        setFileList(res.fileList ?? []);
    };

    const downloadFile = async (path: string, name: string) => {
        const localPath = await min_app_fs.openDialog("保存文件", false, name);
        if (localPath == "") {
            return;
        }

        const api = getSftpApi();
        try {
            await api.sftpDownloadPost({
                sftpDownloadPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    path,
                    localPath,
                },
            });
            message.info("下载成功");
        } catch (e) {
            console.log(e);
            message.error("下载文件失败");
        }
    };

    const remove = async () => {
        const api = getSftpApi();
        try {
            await api.sftpRemovePost({
                sftpListDirPostRequest: {
                    token: getToken(),
                    id: props.curClientId,
                    path: removePath,
                },
            });
            await loadFileList();
            setRemovePath("");
        } catch (e) {
            console.log(e);
            message.error("删除失败");
        }
    };

    const getPathTitle = (fileInfo: FileInfo) => {
        if (fileInfo.dir == true) {
            return fileInfo.path ?? "";
        }
        let size = fileInfo.size ?? 0;
        if (size < 1024) {
            return `${fileInfo.path ?? ""} ${size}B`;
        }
        size = size / 1024;
        if (size < 1024) {
            return `${fileInfo.path ?? ""} ${size.toFixed(1)}K`;
        }
        size = size / 1024;
        if (size < 1024) {
            return `${fileInfo.path ?? ""} ${size.toFixed(1)}M`;
        }
        size = size / 1024;
        return `${fileInfo.path ?? ""} ${size.toFixed(1)}G`;
    }

    useEffect(() => {
        if (props.curClientId == "") {
            setCurPath("");
        } else {
            loadCurPath();
        }
    }, [props.curClientId]);

    useEffect(() => {
        loadFileList();
    }, [curPath]);

    return (
        <Card title="文件系统" style={{ height: "calc(50vh - 50px)", overflowY: "hidden" }} bodyStyle={{ height: "calc(50vh - 110px)", overflowY: "auto", padding: "0px 10px" }}
            extra={
                <Space size="middle">
                    <Button type="text" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowUploadModal(true);
                    }} disabled={curPath == ""}><UploadOutlined /></Button>
                    <Button type="text" style={{ minWidth: 0, padding: "0px 0px" }} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setShowMkdirModal(true);
                    }} disabled={curPath == ""}><FolderAddOutlined /></Button>
                </Space>
            }>
            <List rowKey="path" dataSource={fileList} renderItem={fileInfo => (
                <List.Item title={getPathTitle(fileInfo)} extra={
                    <Space size="small">
                        {fileInfo.dir !== true && (
                            <a style={{ color: "black" }} onClick={e => {
                                e.stopPropagation();
                                e.preventDefault();
                                downloadFile(fileInfo.path ?? "", fileInfo.name ?? "");
                            }}><DownloadOutlined /></a>
                        )}
                        {fileInfo.name != ".." && (
                            <Popover trigger="click" placement="bottom" content={
                                <Space direction="vertical">
                                    <Button type="link" onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setRenamePath(fileInfo.path ?? "");
                                    }}>重命名</Button>
                                    <Button type="link" danger onClick={e => {
                                        e.stopPropagation();
                                        e.preventDefault();
                                        setRemovePath(fileInfo.path ?? "");
                                    }}>删除</Button>
                                </Space>
                            }>
                                <MoreOutlined />
                            </Popover>
                        )}
                    </Space>
                }>
                    <div style={{
                        cursor: fileInfo.dir == true ? "pointer" : undefined, overflow: "hidden",
                        width: "120px", whiteSpace: "nowrap", textOverflow: "ellipsis"
                    }} onClick={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        if (fileInfo.dir == true) {
                            setCurPath(fileInfo.path ?? "");
                        }
                    }}>
                        <Space size="middle">
                            {fileInfo.dir == true && <FolderOutlined />}
                            {fileInfo.dir !== true && <FileOutlined />}
                            <span>{fileInfo.name}</span>
                        </Space>
                    </div>
                </List.Item>
            )} />
            {showMkdirModal == true && (
                <MkdirModal curClientId={props.curClientId} curPath={curPath} onCancel={() => setShowMkdirModal(false)} onOk={() => {
                    loadFileList();
                    setShowMkdirModal(false);
                }} />
            )}
            {showUploadModal == true && (
                <UploadModal curClientId={props.curClientId} curPath={curPath} onCancel={() => setShowUploadModal(false)} onOk={() => {
                    loadFileList();
                    setShowUploadModal(false);
                }} />
            )}
            {renamePath !== "" && (
                <RenameModal curClientId={props.curClientId} srcPath={renamePath} onCancel={() => setRenamePath("")}
                    onOk={() => {
                        loadFileList();
                        setRenamePath("");
                    }} />
            )}
            {removePath !== "" && (
                <Modal open title="删除文件/空目录" okText="删除" okButtonProps={{ danger: true }}
                    onCancel={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        setRemovePath("");
                    }}
                    onOk={e => {
                        e.stopPropagation();
                        e.preventDefault();
                        remove();
                    }}>
                    是否删除&nbsp;{removePath}&nbsp;?
                </Modal>
            )}
        </Card>
    )
}

export default SftpPanel;